怎么使用Python读写二进制文件 您所在的位置:网站首页 python 中文字符 怎么使用Python读写二进制文件

怎么使用Python读写二进制文件

#怎么使用Python读写二进制文件| 来源: 网络整理| 查看: 265

1. 简介

Python 读写文件的二进制数据需要使用到struct模块,进行C/C++与Python数据格式的转换。

2. struct模块介绍

struct模块中最常用的函数为pack和unpack,用法如下:

函数returnexplainpack(fmt,v1,v2…)string按照给定的格式(fmt),把数据转换成字符串(字节流),并将该字符串返回.pack_into(fmt,buffer,offset,v1,v2…)None按照给定的格式(fmt),将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中.(buffer为可写的缓冲区,可用array模块)unpack(fmt,v1,v2……)tuple按照给定的格式(fmt)解析字节流,并返回解析结果pack_from(fmt,buffer,offset)tuple按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果calcsize(fmt)size of fmt计算给定的格式(fmt)占用多少字节的内存,注意对齐方式3. struct模块中数据格式fmt对应C/C++和Python中的类型FormatC TypePython typeStandard sizexpad byteno valueccharstring of length1bsigned charinteger1Bunsigned charinteger1?_Boolbool1hshortinteger2Hunsigned shortinteger2iintinteger4Iunsigned intinteger4llonginteger4Lunsigned longinteger4qlong longinteger8Qunsigned long longinteger8ffloatfloat4ddoublefloat8schar[]stringpchar[]stringPvoid *integer4. 实例

注意:代码中,表示大端

import struct # 打开文件 with open("binary_file.bin", "wb") as f: # 写入4个字节的整数(值为12345) int_value = 12345 f.write(struct.pack("


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有